package info.batcloud.fanli.api.controller;

import info.batcloud.fanli.core.dto.UserDTO;
import info.batcloud.fanli.core.domain.BusinessResponse;
import info.batcloud.fanli.core.enums.UserLevel;
import info.batcloud.fanli.core.helper.SecurityHelper;
import info.batcloud.fanli.core.service.IntegralService;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.service.UserService;
import info.batcloud.fanli.core.settings.IntegralSetting;
import info.batcloud.fanli.core.settings.UserUpgradeSetting;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/page/upgrade-user-level")
public class PageUpgradeUserLevelController {

    @Inject
    private SystemSettingService systemSettingService;

    @Inject
    private UserService userService;

    @Inject
    private IntegralService integralService;

    @GetMapping("/data")
    public Object data() {
        UserUpgradeSetting setting = systemSettingService.findActiveSetting(UserUpgradeSetting.class);
        IntegralSetting integralSetting = systemSettingService.findActiveSetting(IntegralSetting.class);
        Map<String, Object> map = new HashMap<>();
        map.put("userUpgradeSetting", setting);
        map.put("moneyExchangeToIntegral", 1 / integralSetting.getEachIntegralExchangeToMoney());

        Long userId = SecurityHelper.loginUserId();
        UserLevel userLevel = UserLevel.ORDINARY;
        if (userId != null) {
            UserDTO user = userService.findById(userId);
            userLevel = user.getLevel();
            if (userService.isUserLevel(userId, UserLevel.PLUS) && user.getLevelExpireTime() != null) {
                map.put("levelExpireTime", DateFormatUtils.format(user.getLevelExpireTime(), "yyyy年M月d日"));
            }
        }
        map.put("userLevel", userLevel);
        UserLevel nextUserLevel = userLevel.next;
//        if (nextUserLevel.level > UserLevel.PLUS.level) {
//            nextUserLevel = UserLevel.PLUS;
//        }
        if(nextUserLevel == null) {
            map.put("nextUserUpgrade", userLevel);
        } else {
            map.put("nextUserUpgrade", userService.findUpgradeByUserLevel(nextUserLevel));
        }

        map.put("nextUserLevel", nextUserLevel);
        map.put("nextUserLevelTitle", nextUserLevel == null ? null : nextUserLevel.getTitle());
        map.put("userLevelTitle", userLevel.getTitle());
        return BusinessResponse.ok(map);

    }

}
